package com.woniuxy.platform.app.apiImpl;

import cn.hutool.core.bean.BeanUtil;
import com.woniuxy.platform.client.UserQueryClient;
import com.woniuxy.platform.client.param.LoginParam;
import com.woniuxy.platform.client.result.LoginDto;
import com.woniuxy.platform.common.util.JwtUtil;
import com.woniuxy.platform.infra.model.PlatformUser;
import com.woniuxy.platform.service.PlatformUserService;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import result.Result;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/platform")
public class UserQueryClientImpl implements UserQueryClient {

    @Resource
    private PlatformUserService platformUserService;

    @Autowired
    private RedissonClient redissonClient;

    @Override
    public Result<LoginDto> login(@Valid LoginParam param) {
        PlatformUser user = platformUserService.login(param.getAccount(),param.getPassword());
        LoginDto loginDto = BeanUtil.toBean(user,LoginDto.class);
        HashMap<String,Object> body = new HashMap<String,Object>();
        body.put("sub",loginDto.getPlatformUserId());
        String token = JwtUtil.createToken(body, 30);
        String refreshToken = JwtUtil.createToken(body,8*60);
        RBucket<Object> bucket = redissonClient.getBucket(token);
        bucket.set(refreshToken,8*60*60, TimeUnit.SECONDS);
        //将jwt返回
        loginDto.setAccessToken(token);
        return Result.success(loginDto);
    }
}
